package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ChangeOrRefundServlet")
public class ChangeOrRefundServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("success", false);
            request.getRequestDispatcher("ticketRefundOrCancellation.jsp").forward(request, response);
            return;
        }

        String ticketOP = request.getParameter("TicketOP");
        String selectedFlightData = request.getParameter("selectedFlightData");
        String selectedOrderData = request.getParameter("selectedOrderData");
        String orderId = "";

        // 解析订单号
        String cleanedOrderData = selectedOrderData.substring(1, selectedOrderData.length() - 1);
        String[] orderData = cleanedOrderData.split(",");
        orderId = orderData[0].replaceAll("\"", "").trim();

        // 构造请求信息
        Map<String, String> requestInfo = new HashMap<>();
        requestInfo.put("orderId", orderId);
        requestInfo.put("type", ticketOP);
        requestInfo.put("userId", String.valueOf(user.getUid())); // 用户ID
        requestInfo.put("status", "pending"); // 初始状态为待处理

        if ("Change".equals(ticketOP)) {
            // 解析改签的新航班信息
            String cleanedFlightData = selectedFlightData.substring(1, selectedFlightData.length() - 1);
            String[] flightData = cleanedFlightData.split(",");
            String newFid = flightData[0].replaceAll("\"", "").trim();
            String newPosition = flightData[2].replaceAll("\"", "").trim();
            requestInfo.put("newFid", newFid);
            requestInfo.put("newPosition", newPosition);
        }

        // 保存到ServletContext的待处理列表
        List<Map<String, String>> pendingRequests = (List<Map<String, String>>) 
            getServletContext().getAttribute("pendingReschedulingCancellations");
        if (pendingRequests == null) {
            pendingRequests = new ArrayList<>();
        }
        pendingRequests.add(requestInfo);
        getServletContext().setAttribute("pendingReschedulingCancellations", pendingRequests);

        request.setAttribute("success", true);
        request.getRequestDispatcher("ticketRefundOrCancellation.jsp").forward(request, response);
    }
}